from templates import template_render
from urllib2 import HTTPError
import urllib
import web
import simplejson
from printer import  _Printer
from gcp import GoogleCloudPrint
from session import need_auth, AuthBase
import logging

class JobOutput:
    def __init__(self, title, fileLink, ticketLink):
        self.title = title
        self.fileLink = fileLink
        self.ticketLink = ticketLink

class ePrintJobs(AuthBase):
    @need_auth
    def GET(self, printerid):
        self.setSessionCookie()
        session = self.getSession()
        try:
            api = GoogleCloudPrint(user=session.user)
            jobs = api.fetch_print_job(printerid)

            out = []
            for j in jobs:
                logging.info(j.fileUrl)
                f = urllib.urlencode({"url":j.fileUrl})
                logging.info(f)
                t = urllib.urlencode({"url":j.ticketUrl})
                out.append(JobOutput(j.title, f, t))
            return template_render.jobs(user=session and session.user or None, jobs=out)
            
        except HTTPError:
            raise web.seeother('/signin')
        
